package groups

import (
	"encoding/json"
	"strconv"
	"xpms/controllers"
	"xpms/cores/utils"
)

//组成员管理
type ManageGroupUserController struct {
	controllers.BaseController
}

// @Title Get
// @Description get GroupUser by id
// @Param	id		path 	string	true		"The key for GroupUser"
// @Success 200 {object} groups.GroupsUserName
// @Failure 403 :id is empty
// @router /:id [get]
func (u *ManageGroupUserController) GetUserByGroupId() {
	uid := u.GetString(":id")
	if uid != "" {
		int64, _ := strconv.ParseInt(uid, 10, 64)
		_, _, groupuser := ListGroupsUserAndName(int64)
		u.Data["json"] = groupuser
	}
	u.ServeJSON()
}

type AddGroupUser struct {
	GroupId string
	Userid  string
}

// @Title 添加组用户
// @Description 添加组用户
// @Param	body		body 	groups.AddGroupUser	true		"body for AddGroupUser content"
// @Success 200 {string} groups.Groups.Id
// @Failure 403 body is empty
// @router /user [post]
func (u *ManageGroupUserController) AddGroupUser() {
	var group AddGroupUser
	json.Unmarshal(u.Ctx.Input.RequestBody, &group)
	if utils.IsEmpty(group.GroupId) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请选择组"}
		u.ServeJSON()
		return
	} else if utils.IsEmpty(group.Userid) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请选择需要添加的用户"}
		u.ServeJSON()
		return
	}
	int64, _ := strconv.ParseInt(group.GroupId, 10, 64)
	condArr := make(map[string]interface{})
	condArr["userid"] = group.Userid
	condArr["groupid"] = int64
	exitsUser, err := GetGroupByUser(group.GroupId, group.Userid)
	if err != nil || !utils.IsEmpty(exitsUser) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "用户已存在"}
		u.ServeJSON()
		return
	}

	id := utils.SnowFlakeId()
	gu := new(GroupsUser)
	gu.Id = id
	gu.Groupid = int64
	vint64, _ := strconv.ParseInt(group.Userid, 10, 64)
	gu.Userid = vint64
	err = AddGroupsUser(*gu)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "操作成功", "id": group.GroupId}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "添加失败"}
	}
	u.ServeJSON()
}

// @Title Delete
// @Description delete the group
// @Param	body	 body 	[]string	true		"The ids you want to delete groupUser id"
// @Success 200
// @Failure 403 id is empty
// @router /user [delete]
func (u *ManageGroupUserController) DeleteGroupUser() {
	var ids []string
	json.Unmarshal(u.Ctx.Input.RequestBody, &ids)
	if utils.IsEmpty(ids) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请选择要删除的用户"}
		u.ServeJSON()
		return
	}
	err := DeleteGroupsUsers(ids)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "删除成功"}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "删除失败"}
	}
	u.ServeJSON()
}
